package org.framework.lazy.cloud.network.heartbeat.client.netty.proxy.socks.advanced;

import io.netty.channel.Channel;
import io.netty.handler.codec.socksx.v5.DefaultSocks5CommandResponse;
import io.netty.handler.codec.socksx.v5.Socks5AddressType;
import io.netty.handler.codec.socksx.v5.Socks5CommandStatus;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.proxy.socks.client.AbstractHandleSocksDistributeClientProxyClientTransferCloseTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Role;
import org.wu.framework.core.utils.ObjectUtils;

@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Slf4j
public class ClientHandleDistributeSocksClientProxyClientTransferCloseAdvanced extends
        AbstractHandleSocksDistributeClientProxyClientTransferCloseTypeAdvanced<NettyProxyMsg> {


    /**
     * 处理当前数据
     *
     * @param nettyChannelContext 当前通道
     * @param nettyProxyMsg       通道数据
     */
    @Override
    protected void doHandler(NettyChannelContext nettyChannelContext, NettyProxyMsg nettyProxyMsg) {
        Channel channel = nettyChannelContext.channel();
        // 关闭传输通道
        Channel visitorChannel = ChannelAttributeKeyUtils.getNextChannel(channel);

        channel.close(); // 数据传输通道关闭

        if (ObjectUtils.isNotEmpty(visitorChannel)) {
            Byte socks5AddressTypeByte = ChannelAttributeKeyUtils.getSocks5AddressType(visitorChannel);
            Socks5AddressType socks5AddressType = Socks5AddressType.valueOf(socks5AddressTypeByte);
            DefaultSocks5CommandResponse commandResponse =
                    new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, socks5AddressType);
            visitorChannel.writeAndFlush(commandResponse);
            visitorChannel.close();// 真实通道关闭
        }

    }
}
